package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.ScheduleConstants;
import com.ruoyi.common.core.domain.entity.system.SysJob;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.common.utils.CronUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.domain.entity.system.SysScenicJob;
import com.ruoyi.job.utils.ScheduleUtils;
import com.ruoyi.system.mapper.SysJobMapper;
import com.ruoyi.system.mapper.SysScenicJobMapper;
import com.ruoyi.system.service.ISysJobService;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 定时任务调度信息 服务层
 *
 * @author ruoyi
 */
@Service
public class SysJobServiceImpl implements ISysJobService {
    @Autowired
    private Scheduler scheduler;

    @Autowired
    private SysJobMapper jobMapper;

    @Autowired
    private SysScenicJobMapper scenicJobMapper;

    /**
     * 项目启动时，初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException {
        scheduler.clear();
        List<SysJob> jobList = jobMapper.selectJobAll();
        for (SysJob job : jobList) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    /**
     * 获取quartz调度器的计划任务列表
     *
     * @param job 调度信息
     * @return
     */
    @Override
    public List<SysJob> selectJobList(SysJob job) {
        return jobMapper.selectJobList(job);
    }

    /**
     * 通过调度任务ID查询调度信息
     *
     * @param jobId 调度任务ID
     * @return 调度任务对象信息
     */
    @Override
    public SysJob selectJobById(Long jobId) {
        return jobMapper.selectJobById(jobId);
    }

    /**
     * 根据创建者名称与任务组名查找任务。
     *
     * @param createBy
     * @param jobGroup
     * @return
     */
    public SysJob selectJobByCreatorAndGroup(String createBy, String jobGroup) {
        return jobMapper.selectJobByCreatorAndGroup(createBy, jobGroup);
    }


    /**
     * 暂停任务
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int pauseJob(SysJob job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = jobMapper.updateJob(job);
        if (rows > 0) {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 恢复任务
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int resumeJob(SysJob job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        int rows = jobMapper.updateJob(job);
        if (rows > 0) {
            scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 删除任务后，所对应的trigger也将被删除
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteJob(SysJob job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        int rows = jobMapper.deleteJobById(jobId);
        if (rows > 0) {
            scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 批量删除调度信息
     *
     * @param jobIds 需要删除的任务ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteJobByIds(Long[] jobIds) throws SchedulerException {
        for (Long jobId : jobIds) {
            SysJob job = jobMapper.selectJobById(jobId);
            deleteJob(job);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteJobByScenicAdmin(Long scenicId, String jobGroup) throws SchedulerException {
        List<Long> jobIds = scenicJobMapper.getJobIdsByScenicId(scenicId);
        if (Objects.isNull(jobIds) || jobIds.size() < 1) return;

        List<SysJob> jobs = jobIds.stream().map(jobId -> jobMapper.selectJobById(jobId))
                .filter(sysJob -> sysJob.getJobGroup().equals(jobGroup)).collect(Collectors.toList());

        for (SysJob job : jobs) {
            deleteJob(job);
        }
        Long[] needJobIds = jobs.stream().map(SysJob::getJobId).toArray(Long[]::new);
        scenicJobMapper.deleteScenicJob(needJobIds);
    }

    /**
     * 任务调度状态修改
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changeStatus(SysJob job) throws SchedulerException {
        int rows = 0;
        String status = job.getStatus();
        if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
            rows = resumeJob(job);
        } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
            rows = pauseJob(job);
        }
        return rows;
    }

    /**
     * 立即运行任务
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean run(SysJob job) throws SchedulerException {
        boolean result = false;
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        SysJob properties = selectJobById(job.getJobId());
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            result = true;
            scheduler.triggerJob(jobKey, dataMap);
        }
        return result;
    }

    /**
     * 新增任务
     *
     * @param job 调度信息 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertJob(SysJob job) throws SchedulerException, TaskException {
//        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = jobMapper.insertJob(job);
        if (rows > 0) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
        return rows;
    }

    /**
     * 由景区管理员新增定时任务。
     *
     * @param scenicId
     * @param job
     * @return
     * @throws SchedulerException
     * @throws TaskException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertJobByScenicAdmin(Long scenicId, SysJob job) throws SchedulerException, TaskException {
        int rows = jobMapper.insertJob(job);
        if (rows > 0) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
        SysScenicJob sysScenicJob = new SysScenicJob();
        sysScenicJob.setScenicId(scenicId);
        sysScenicJob.setJobId(job.getJobId());
        scenicJobMapper.insertScenicJob(sysScenicJob);

        return rows;
    }

    /**
     * 由景区管理员批量新增定时任务。
     *
     * @param scenicId
     * @param jobs
     * @return
     * @throws SchedulerException
     * @throws TaskException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addJobsByScenicAdmin(Long scenicId, List<SysJob> jobs) throws SchedulerException, TaskException {
        for (SysJob job : jobs) {
            if (!CronUtils.isValid(job.getCronExpression())) {
                throw new TaskException("新增任务'" + job.getJobName() + "'失败，Cron表达式不正确", TaskException.Code.CONFIG_ERROR);
            } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
                throw new TaskException("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用", TaskException.Code.CONFIG_ERROR);
            } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
                throw new TaskException("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用", TaskException.Code.CONFIG_ERROR);
            } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
                throw new TaskException("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用", TaskException.Code.CONFIG_ERROR);
            } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
                throw new TaskException("新增任务'" + job.getJobName() + "'失败，目标字符串存在违规", TaskException.Code.CONFIG_ERROR);
            } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
                throw new TaskException("新增任务'" + job.getJobName() + "'失败，目标字符串不在白名单内", TaskException.Code.CONFIG_ERROR);
            }
        }
        int rows = 0;
        for (SysJob job : jobs) {
            job.setCreateBy(SecurityUtils.getUsername());
            int row = jobMapper.insertJob(job);
            if (row > 0) {
                rows++;
                ScheduleUtils.createScheduleJob(scheduler, job);
                SysScenicJob sysScenicJob = new SysScenicJob();
                sysScenicJob.setScenicId(scenicId);
                sysScenicJob.setJobId(job.getJobId());
                scenicJobMapper.insertScenicJob(sysScenicJob);
            }
        }
        return rows;
    }

    /**
     * 更新任务的时间表达式
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateJob(SysJob job) throws SchedulerException, TaskException {
        SysJob properties = selectJobById(job.getJobId());
        int rows = jobMapper.updateJob(job);
        if (rows > 0) {
            updateSchedulerJob(job, properties.getJobGroup());
        }
        return rows;
    }

    /**
     * 更新任务
     *
     * @param job      任务对象
     * @param jobGroup 任务组名
     */
    public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException {
        Long jobId = job.getJobId();
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }


    public void updateJobByScenicAdmin(Long scenicId, String jobGroup) {

    }

    /**
     * 校验cron表达式是否有效
     *
     * @param cronExpression 表达式
     * @return 结果
     */
    @Override
    public boolean checkCronExpressionIsValid(String cronExpression) {
        return CronUtils.isValid(cronExpression);
    }


}
